package com.cheng.system.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cheng.common.constants.RedisKey;
import com.cheng.common.exception.CustomException;
import com.cheng.system.dao.UserMapper;
import com.cheng.system.model.User;
import com.cheng.system.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author 起凡
 * @since 2021-09-25
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Autowired
    RedisTemplate<String, Object> redisTemplate;

    @Override
    public boolean plusUserMoney(BigDecimal money, Long id) {
        Boolean flag = redisTemplate.opsForValue().setIfAbsent(RedisKey.UPDATE_USER_MONEY_KEY + StpUtil.getLoginIdAsString(),
                1, 10, TimeUnit.SECONDS);
        if (flag) {
            User user = getById(id);
            user.setTotalMoney(user.getTotalMoney().add(money));
            updateById(user);
            //释放锁
            redisTemplate.delete(RedisKey.UPDATE_USER_MONEY_KEY + StpUtil.getLoginIdAsString());
            return true;
        }
        throw new CustomException("操作频繁请重新尝试");
    }

    @Override
    public boolean minusUserMoney(BigDecimal money, Long id) {

        Boolean flag = redisTemplate.opsForValue().setIfAbsent(RedisKey.UPDATE_USER_MONEY_KEY + StpUtil.getLoginIdAsString(),
                1, 10, TimeUnit.SECONDS);
        if (flag) {
            User user = getById(id);
            user.setTotalMoney(user.getTotalMoney().subtract(money));
            updateById(user);
            //释放锁
            redisTemplate.delete(RedisKey.UPDATE_USER_MONEY_KEY + StpUtil.getLoginIdAsString());
            return true;
        }
        throw new CustomException("操作频繁请重新尝试");

    }
}
